<template>
	<view class="scan-code">
		<view class="top">
			<view style="font-size: 18px;">{{appInfo.name}}</view>
		</view>
		<scroll-view v-if="isNull(barCodes)" class="center">
			<view class="u-null">
				<!-- <text>v{{appInfo.version}}</text> -->
				<text>长按扫码按钮可手动添加条码</text>
			</view>
		</scroll-view>
		<scroll-view v-else class="center" scroll-y="true" scroll-with-animation="true" :scroll-into-view="codesVId">
			<uni-swipe-action>
				<uni-swipe-action-item class="item" v-for="(item, index) in barCodes" :key="item.id" :id="item.id"
					:right-options="usaOptions" @click="bindClick($event, item.code)"
					@change="swipeChange($event,index)">
					<view class="u-item">
						<view class="ino">{{index + 1}}.</view>
						<view class="code">{{item.code}}</view>
						<view class="mem">
							<text @click="handMem(item.code,item.mem)">{{item.mem == '' ? '点击此处添加备注' : item.mem}}</text>
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
		</scroll-view>
		<view class="bottom">
			<button type="warn" @click="clearCode">清空</button>
			<icon class="iconfont icon-saoma" type="" @click="scanCode" @longpress="handCode('')"></icon>
			<!-- <button @click="submitCode">提交</button> -->
			<button @click="exportCode">导出</button>
		</view>
		<!-- 备注/条码 输入框 -->
		<uni-popup class="u-pop" ref="ppMem" type="top" :animation="true">
			<view class="u-inner">
				<view class="u-top">
					<text>{{cfmParm.title}}</text>
				</view>
				<view class="u-center">
					<uni-easyinput focus class="u-input" v-model="mValue" type="text"
						:placeholder="cfmParm.flag == 'editCode'?'请输入条码':'请输入备注'">
					</uni-easyinput>
				</view>
				<view class="u-bottom">
					<button @click="ppConfirm('ppMem')">确认</button>
				</view>
			</view>
		</uni-popup>
		<!-- 确认框 -->
		<uni-popup ref="ppCfm" type="dialog">
			<uni-popup-dialog :type="cfmParm.type" :title="cfmParm.title" :content="cfmParm.content"
				:before-close="true" @close="ppClose('ppCfm')" @confirm="ppConfirm('ppCfm')">
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	const app = getApp({
		allowDefault: true
	})
	const platForm = uni.getStorageSync('platForm')
	import util from "../../static/js/util.js"
	export default {
		data() {
			return {
				codesVId: '',
				barCodes: [],
				userInfo: null,
				mValue: '',
				usaOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d',
					}
				}, {
					text: '修改',
					style: {
						backgroundColor: '#f0ad4e',
					}
				}],
				cfmParm: {
					flag: '',
					type: '',
					title: '',
					content: '',
				},
				appInfo: null
			}
		},
		methods: {
			init() {
				this.userInfo = uni.getStorageSync('erpUserInfo')
				this.appInfo = uni.getStorageSync('appWgtInfo') || {name: '扫码导出Excel',version: '1.0.1'}
				// console.log(this.appInfo)
			},
			// 扫码或手动加入条码
			handCode(c) {
				this.cfmParm.flag = 'editCode'
				this.cfmParm.type = 'warn'
				this.cfmParm.title = util.isNull(c) ? '新增条码' : '编辑条码' + c
				this.cfmParm.content = util.isNull(c) ? '' : c
				this.mValue = c
				this.ppOpen('ppMem')
			},
			scanCode() {
				uni.scanCode({
					success: (r) => {
						this.setCode('new', r.result)
					},
					fail: (e) => {
						console.log(e)
						// uni.showToast({
						// 	title: e.errMsg,
						// 	icon: 'none'
						// })
					}
				})
			},
			// 长按扫码按钮显示微信扫一扫界面（如何返回值）
			scanCodeWX() {
				// console.log(plus.os.name)
				if (plus.os.name == "iOS") {
					plus.runtime.openURL("weixin://scanqrcode")
				} else if (plus.os.name == "Android") {
					try {
						var Intent = plus.android.importClass("android.content.Intent");
						var ComponentName = plus.android.importClass('android.content.ComponentName')
						var intent = new Intent();
						intent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI"));
						intent.putExtra("LauncherUI.From.Scaner.Shortcut", true);
						intent.setFlags(335544320);
						intent.setAction("android.intent.action.VIEW");
						var main = plus.android.runtimeMainActivity();
						main.startActivity(intent);
					} catch (e) {
						uni.showToast({
							title: e.errMsg,
							icon: 'none'
						})
					}
				}
			},
			// 条码插入
			setCode(type, code) {
				let _title = ''
				let b = this.barCodes || []
				let checkCode = null
				if (type == 'new') checkCode = code
				if (type == 'edit') checkCode = this.mValue
				if((type == 'new' || type == 'edit') && util.isNull(checkCode)) _title = '请输入条码'
				for (let i in b) {
					b[i].id = 'codeId' + i
					if (checkCode == b[i].code) {
						_title = checkCode + '已存在'
					}
				}
				if (util.isNull(_title)) {
					let bl = b.length || 0
					if (type == 'new') {
						let newCode = {}
						newCode.id = 'codeId' + bl
						newCode.code = code
						newCode.mem = ''
						b.push(newCode)
						this.barCodes = b
						this.codesVId = newCode.id
					} else {
						let ii = -1
						for (let i in b) {
							if (code == b[i].code) ii = i
						}
						if (type == 'edit') {
							b[ii].code = this.mValue
						}
						if (type == 'mem') {
							b[ii].mem = this.mValue
						}
						if (type == 'del') {
							b.splice(ii, 1)
						}
						this.barCodes = b
					}
					return true
				} else {
					uni.showToast({
						title: _title,
						icon: 'none',
					})
					return false
				}
			},
			// 修改备注
			handMem(c, m) {
				this.cfmParm.flag = 'memCode'
				this.cfmParm.type = 'info'
				this.cfmParm.title = c + '的备注'
				this.cfmParm.content = c
				this.mValue = m
				this.ppOpen('ppMem')
			},
			// 清除
			clearCode() {
				this.cfmParm.flag = 'clearCode'
				this.cfmParm.type = 'error'
				this.cfmParm.title = '是否清空所有条码'
				this.cfmParm.content = ''
				this.ppOpen('ppCfm')
			},
			// 提交
			submitCode() {
				let u = this.userInfo
				let b = this.barCodes
				let s = ''
				if (util.isNull(b)) s = '请先扫码'
				if (util.isNull(s)) {
					this.cfmParm.flag = 'submitCode'
					this.cfmParm.type = 'success'
					this.cfmParm.title = '是否提交所有条码'
					this.cfmParm.content = ''
					this.ppOpen('ppCfm')
				} else {
					uni.showToast({
						title: s,
						icon: 'none',
					})
				}
			},
			// 模态框打开关闭确认
			ppOpen(n) {
				if (n == 'ppLogin') {
					let appInfo = uni.getStorageSync('appWgtInfo')
					// console.log(appInfo)
					this.userInfo = util.isNull(appInfo) ? '扫码工具v1.0' : appInfo.name + 'v' + appInfo.version
					return
				}
				this.$refs[n].open()
			},
			ppClose(n) {
				this.$refs[n].close()
			},
			ppConfirm(n) {
				// console.log(this.cfmParm)
				let p = this.cfmParm
				if (p.flag == 'editCode') {
					let t = util.isNull(p.content) ? 'new' : 'edit'
					let c = util.isNull(p.content) ? this.mValue : p.content
					if (this.setCode(t, c)) this.$refs[n].close()
				} else if (p.flag == 'memCode') {
					let t = 'mem'
					let c = util.isNull(p.content) ? this.mValue : p.content
					if (this.setCode(t, c)) this.$refs[n].close()
				} else {
					if (p.flag == 'submitCode') {
						let u = this.userInfo
						let b = this.barCodes
						this.submitCodeDone(u, b)
					}
					if (p.flag == 'clearCode') {
						this.barCodes = []
					}
					this.$refs[n].close()
				}
			},
			// 滑动功能按钮
			bindClick(e, c) {
				// console.log(e, c)
				if (e.content.text == '删除') {
					this.setCode('del', c)
				}
				if (e.content.text == '修改') {
					this.handCode(c)
				}
			},
			swipeChange(e, index) {
				// console.log('滑动按钮切换当前状态：' + e + '，下标：' + index)
			},
			// 导出数据
			exportCode() {
				let b = this.barCodes
				if (util.isNull(b)) {
					uni.showToast({
						title: '请先扫码',
						icon: 'none',
					})
				} else {
					// console.log(platForm)
					if (platForm == 'app') 
						this.app2Excel(b)
					else 
						this.createExcelHttp(b)
				}
			},
			// android 导出excel
			app2Excel(b) {	
				let jsonData = []
				let str = '<tr><td>序号</td><td>条码</td><td>备注</td></tr>'
				for(let i in b) {
					let data = {}
					data.ino = i*1+1
					data.code = b[i].code
					data.mem = b[i].mem
					jsonData.push(data)
				}
				util.appExportFile(jsonData, str)	
			},
			// 在后台生成excel并下载
			createExcelHttp(b) {
				let jsonData = [['序号','条码','备注']]
				for(let i in b) {
					let data = [i*1+1, b[i].code, b[i].mem]
					jsonData.push(data)
				}
				let _url = 'https://galaha.top/api/Appmgt/createExcel?excel_data='+JSON.stringify(jsonData)
				// console.log(_url)
				uni.showToast({
					title: '加载中……',
					icon: 'loading',
					mask: true,
				})
				let _duration = 3500
				uni.downloadFile({
					url: _url,
					success: (d_res) => {
						// console.log(d_res)
						let p = d_res.tempFilePath
						uni.saveFile({
							tempFilePath:p,
							success: (s_res) => {
								// console.log(s_res)
								let p = s_res.savedFilePath
								uni.openDocument({
									showMenu: true,
									filePath:p,
									success: (o_res) => {
										// console.log(o_res)
									},
									fail: (e) => {
										console.log(e)
										uni.showToast({
											title: '文件打开失败，'+e.errMsg,
											icon: 'none',
											duration: _duration
										})
									}
								})
							},
							fail: (e) => {
								console.log(e)
								uni.showToast({
									title: '文件保存失败，'+e.errMsg,
									icon: 'none',
									duration: _duration
								})
							}
						})
					},
					fail:(e) =>{
						console.log(e)
						uni.showToast({
							title: '文件下载失败，'+e.errMsg,
							icon: 'none',
							duration: _duration
						})
					}
				})
			},
			// 登录信息
			loginDone(e) {
				console.log(e)
				if (!util.isNull(e).id) {
					this.userInfo = e
					uni.setStorage({
						key: 'erpUserInfo',
						data: this.userInfo
					})
				}
				this.$refs['ppLogin'].close()
			},
			logOut() {
				this.userInfo = null
				uni.clearStorage('erpUserInfo')
			},
			isNull(s) {
				return util.isNull(s)
			},
			// 向数据库提交条，条码数据
			submitCodeDone(u, b) {
				uni.request({
					// 可将结果上传到服务器数据库
				})
			},
		},
		onShow() {
			this.init()
		}
	}
</script>

<style lang="scss" scoped>
	.scan-code {
		height: calc(100vh);

		%c-view {
			width: 100%;
			height: auto;
			display: flex;
			align-items: center;
			justify-content: center;
			box-sizing: border-box;
		}

		.top {
			@extend %c-view;
			justify-content: space-between;
			height: 180rpx;
			background-color: #F0F0F0;
			padding: 0 30rpx;
			padding-top: 60rpx;

			.info {
				color: #999;
				font-size: 20px;
			}

			.user {
				color: #666;

				text {
					color: $uni-color-primary;
					font-size: 22px;
					font-weight: 900;
				}
			}
		}

		.center {
			@extend %c-view;
			height: calc(100vh - 330rpx);

			.item {
				width: 100%;
				min-height: 150rpx;
				background-color: #fff;

				.u-item {
					@extend %c-view;
					width: 100%;
					min-height: 150rpx;
					flex-direction: column;
					position: relative;
					padding-left: 60rpx;

					view {
						@extend %c-view;
						justify-content: flex-end;
						flex: 1;
						padding: 10rpx 20rpx;
					}

					.ino {
						position: absolute;
						left: 0;
						width: 60rpx;
						height: 100%;
						justify-content: center;
						font-size: 24px;
						font-weight: 900;
						font-style: italic;
					}

					.code {
						font-size: 18px;
						font-weight: 900;
					}

					.mem {
						font-size: 14px;
						color: #999;
					}
				}
			}

			.item:nth-child(even) {
				background-color: #eee;
			}

			.u-null {
				@extend %c-view;
				height: 600rpx;
				color: #ccc;
			}
		}

		.bottom {
			@extend %c-view;
			height: 150rpx;
			background-color: #fff;
			box-shadow: 1px 1px 5px #999;

			.iconfont {
				font-size: 150rpx;
				color: $uni-color-success;
				background-color: #f9f9f9;
				border-radius: 20rpx;
				box-shadow: 1px 1px 1px #999;
				margin-top: -60px;
				padding: 5rpx;
				z-index: 1;
			}
		}

		.u-pop {
			margin-top: -150rpx;

			.u-inner {
				@extend %c-view;
				padding-top: 100rpx;
				flex-direction: column;
				background-color: #fff;

				view {
					@extend %c-view;
					padding: 30rpx;
				}

				.u-top {
					font-size: 16px;
					font-weight: 900;
				}

				.u-center {
					padding: 50rpx;
					border: 1px solid #eee;
					.u-input{
						width: 90%;
						// #ifdef APP-PLUS
						width: auto;
						// #endif
					}
				}

				.u-bottom {
					button {
						width: 50%;
						border-radius: 50rpx;
					}
				}
			}
		}
	}
</style>
